import { upload } from '@/services/user';
import type { storageKey } from '@/utils/utils';
import { parse } from 'querystring';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// For the official demo site, it is used to turn off features that are not needed in the real development environment
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export function setStorage<T extends keyof storageKey>(key: T, obj: storageKey[T]) {
  window.localStorage.setItem(key, JSON.stringify(obj));
}

export function getStorage<T extends keyof storageKey>(key: T): storageKey[T] {
  let str = window.localStorage.getItem(key);
  str = str === 'undefined' ? '{}' : str;
  return JSON.parse(str || '{}');
}

export function prefix<T extends keyof request.prefixType = any>(p: T) {
  return (name: keyof request.prefixType[T]) => `${p}/${name}`;
}

export function handleUpload(e) {
  const form = new FormData();
  form.append('file', e.file);
  console.log(form);
  upload(form).then((res) => {
    console.log(res);
  });
}
